﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using AtletIS.Shared.Entities;
using AtletIS.Shared.Data.aDbDataSetTableAdapters;
using AtletIS.Shared.Helpers;
using AtletIS.Shared.Data;

namespace AtletIS.Shared.Forms
{
    public partial class frmWindSpeed : Form
    {
        private DisciplineListTableAdapter taDisciplineList = new DisciplineListTableAdapter();
        private PerformancesTableAdapter taPerformances = new PerformancesTableAdapter();
        private ExtTextsTableAdapter taExtTexts = new ExtTextsTableAdapter();
        private DataTable dtPerformances, dtExtTexts;
        private DisciplineListEntity discipline;
        
        // Constructor
        public frmWindSpeed(DisciplineListEntity discipline)
        {
            InitializeComponent();

            this.discipline = discipline;
            this.Icon = Properties.Resources.Windspeed64;
        }

        // Form Load
        private void frmWindSpeed_Load(object sender, EventArgs e)
        {
            
            // Get performances
            dtPerformances = DatabaseHelper.GetPerformancesByDisciplineListId(Globals.ActiveDiscipline.ID);
            dtPerformances.DefaultView.Sort = "Lane ASC, SB ASC, PB ASC, StartNumber ASC, Surname ASC";
            dtPerformances = dtPerformances.DefaultView.ToTable();

            // Title
            lblTitle.Text += ": " + Globals.ActiveDiscipline.Name + " (" + dtPerformances.Rows.Count.ToString() + ")";

            // Create table header for 6attempts
            if (discipline.DisciplineCode == 4)
            {
                for (int i = 0; i < 6; i++)
                { dtPerformances.Columns.Add((i + 1).ToString()); }

                // Create layout
                dgvResults.DataSource = dtPerformances;
                Helpers.DgvLayoutHelper.SixAttempsLayout(dgvResults);
            }

            // Read ext.texts
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                foreach (DataGridViewRow dgvr in dgvResults.Rows)
                {
                    DataRowView drv = (DataRowView)dgvr.DataBoundItem;
                    if (drv != null)
                    {
                        DataRow dr = (DataRow)drv.Row;
                        int performanceId = Convert.ToInt32(dr["ID"]);

                        dtExtTexts = DatabaseHelper.GetExtTextsByPerformanceIdActive(performanceId); // taExtTexts.GetByPerfId(performanceId);
                        foreach (DataRow drExtText in dtExtTexts.Rows)
                        {
                            dgvResults.Rows[dgvr.Index].Cells[drExtText["Header"].ToString()].Value = drExtText["Text2"].ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace, "WindSpeed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        // Cell end edit
        private void dgvResults_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            string cellValue, performanceId, headerText;

            try
            {
                cellValue = dgvResults.CurrentCell.Value.ToString();
                performanceId = dgvResults.Rows[e.RowIndex].Cells["ID"].Value.ToString();
                headerText = dgvResults.Columns[e.ColumnIndex].Name.ToString();

                aDbDataSet.ExtTextsDataTable dtExtTexts = DatabaseHelper.GetExtTextsByPerformanceIdHeaderAll(Convert.ToInt32(performanceId), headerText);

                #region Insert ext. text

                if (dtExtTexts.Rows.Count == 0)
                {
                    if (!string.IsNullOrEmpty(cellValue))
                    {
                        aDbDataSet.PerformancesRow performancesRow = (aDbDataSet.PerformancesRow)DatabaseHelper.GetPerformancesById(Convert.ToInt32(performanceId)).Rows[0];
                        aDbDataSet.ExtTextsCodesRow extTextsCodesRow = (aDbDataSet.ExtTextsCodesRow)DatabaseHelper.GetExtTextsCodesById(1).Rows[0];

                        dtExtTexts.AddExtTextsRow(performancesRow, null, headerText,
                            Num1: 0, Num2: 0, Text1: null, Text2: cellValue,
                            WebId: 0, Active: true, Sync: false, Modified: DateTime.Now, parentExtTextsCodesRowByFK_ExtTexts_ExtTextsCodes: extTextsCodesRow, VersionInfo: null);
                    }
                    else
                    {
                        dgvResults.CurrentCell.Value = DBNull.Value;
                    }
                }

                #endregion

                #region Update ext. text

                if (dtExtTexts.Rows.Count == 1)
                {
                    if (!string.IsNullOrEmpty(cellValue))
                        dtExtTexts.Rows[0]["Text2"] = cellValue;
                    else
                    {
                        dtExtTexts.Rows[0]["Text2"] = DBNull.Value;

                        dgvResults.CurrentCell.Value = DBNull.Value;
                    }

                    dtExtTexts.Rows[0]["Modified"] = DateTime.Now;
                    taExtTexts.Update(dtExtTexts.Rows[0]);
                }

                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "WindSpeed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }







    }
}
